﻿@page "/Token"
@using System.Text.Json
@using System.Security.Claims
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

@inject IAccessTokenProvider AuthorizationService
@inject NavigationManager Navigation

@if (!_loading)
{
    <h2>Access token for the user</h2>
    <p id="access-token">@AccessToken?.Value</p>

    <h2>Access token claims</h2>
    @foreach (var claim in GetAccessTokenClaims())
    {
        <p>@(claim.Key): @claim.Value.ToString()</p>
    }

    @if (AccessToken != null)
    {
        <h2>Access token expires</h2>
        <p>Current time: <span id="current-time">@DateTimeOffset.Now</span></p>
        <p id="access-token-expires">@AccessToken.Expires</p>

        <h2>Access token granted scopes (as reported by the API)</h2>
        @foreach (var scope in AccessToken.GrantedScopes)
        {
            <p>Scope: @scope</p>
        }
    }
}
else
{
    <div>Loading user data...</div>
}

@code {
    private bool _loading = true;
    [CascadingParameter] private Task<AuthenticationState> AuthenticationState { get; set; }

    public ClaimsPrincipal AuthenticatedUser { get; set; }
    public AccessToken AccessToken { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var state = await AuthenticationState;
        var accessTokenResult = await AuthorizationService.RequestAccessToken(new AccessTokenRequestOptions
            {
                Scopes = new[] { "SecondAPI" }
            });

        if (!accessTokenResult.TryGetToken(out var token))
        {
            Navigation.NavigateToLogin(accessTokenResult.InteractiveRequestUrl, accessTokenResult.InteractionOptions);
            return;
        }

        AccessToken = token;

        AuthenticatedUser = state.User;
        _loading = false;
    }

    protected IDictionary<string, object> GetAccessTokenClaims()
    {
        if (AccessToken == null)
        {
            return new Dictionary<string, object>();
        }

        // header.payload.signature
        var payload = AccessToken.Value.Split(".")[1];
        var base64Payload = payload.Replace('-', '+').Replace('_', '/').PadRight(payload.Length + (4 - payload.Length % 4) % 4, '=');
        return JsonSerializer.Deserialize<IDictionary<string, object>>(Convert.FromBase64String(base64Payload));
    }
}
